package org.coco.mybatis;

import lombok.extern.slf4j.Slf4j;
import org.coco.core.BeanContainer;
import org.coco.core.postprocessor.BeanDefinitionRegistryPostProcessor;
import org.coco.mybatis.xml.DocumentReader;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Spring与MyBatis整合入口，MyBatis通过实现后置处理器来实现配置文件解析
 */
@Slf4j
public class MapperScannerConfigurer implements BeanDefinitionRegistryPostProcessor {

    private static boolean flag = false;

    public static final String FILE_PROTOCOL = "file";

    @Override
    public void postProcessBeanDefinitionRegistry(BeanContainer beanContainer) throws Exception {
        //判断该方法是否被执行过了，如果被执行过了就不需要执行了
        if(flag) {
            return;
        }
        //开始解析MyBatis配置了sql的xml配置文件
        //1：获取某个路径下所有的*.xml配置文件
        List<String> files = getAllXMLFileByPackage("mapper/*.xml");
        new DocumentReader(files).parseDocument();
        flag = true;
    }

    private List<String> getAllXMLFileByPackage(String resourceUrl) throws Exception{
        List<String> fileList = new ArrayList<>();
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        URL resource = classLoader.getResource("");
        String path = resource.getPath()+resourceUrl;
        String url = path.replace("/*.xml", "");
        File fileResource = new File(url);
        if(!fileResource.isDirectory()) {
            log.warn("该文件不是个文件夹:" + resourceUrl);
            return null;
        }
        File[] files = fileResource.listFiles();
        for(File file : files) {
            if(file.isDirectory()) {
                continue;
            }
            String name = file.getName();
            if(name.endsWith(".xml")) {
                fileList.add(file.getPath());
            }
        }
        return fileList;
    }


}
